var snake = (function(window, document) {
	var snake = {
		data: {
			dom: document.getElementById('dan'),
			list: [],
			dir: 'left',
			lists: [],
			j: 0,
			k: 0,
			score: 0,
			drution: 500,
			t: null,
			socket: null
		},
		initsnake: function() {
			this.data.socket = io()

			this.data.list = []

			document.getElementById('game-over').style.display = 'none'
			var h = document.body.offsetHeight
			var num = Math.ceil(h / 50) - 2
			var l = document.body.offsetWidth
			var num2 = Math.ceil(l / 50) - 2
			var p = snake.util.randomRange(0, num)
			var p2 = snake.util.randomRange(0, num2)
			snake.data.list.push({
				x: p2,
				y: p,
				dir: 'left',
				src: './img/headL.png',
				name: sessionStorage.getItem('name')
			})
			this.data.socket.emit('join', snake.data.list)
			this.methods.reciveSocket()
			this.bindevent()
            this.data.socket.emit('sdan')  
			this.methods.loopani()
			
			
		},
		util: {
			randomRange: function(low, high) {
				return Math.ceil(Math.random() * (high - low) + low)
			}
		},
		methods: {
			reciveSocket: function() {
				snake.data.socket.on('setdan',function(data){
					snake.methods.setDan(data)
				})
				snake.data.socket.on('dosetdan',function(data){
					snake.methods.setDan(data)
				})
				snake.data.socket.on('dojoin', function(data) {
					$('img:not(#dan)').remove()
					for(var i = 0; i < data.length; i++) {

						snake.methods.stratPosition(data[i])
					}

				})
				snake.data.socket.on('dotop', function(data) {
					snake.data.lists = data.data

					for(var i = 0; i < snake.data.lists.length; i++) {
						if(snake.data.lists[i][0].name == data.name) {

							document.getElementsByClassName(snake.data.lists[i][data.index].name)[data.index].style.top = document.getElementsByClassName(snake.data.lists[i][data.index].name)[data.index].offsetTop - 50 + 'px'

						}
					}

				})

				snake.data.socket.on('dodown', function(data) {
					snake.data.lists = data.data

					for(var i = 0; i < snake.data.lists.length; i++) {
						if(snake.data.lists[i][0].name == data.name) {

							document.getElementsByClassName(snake.data.lists[i][data.index].name)[data.index].style.top = document.getElementsByClassName(snake.data.lists[i][data.index].name)[data.index].offsetTop + 50 + 'px'

						}
					}

				})

				snake.data.socket.on('doleft', function(data) {
					snake.data.lists = data.data

					for(var i = 0; i < snake.data.lists.length; i++) {
						if(snake.data.lists[i][0].name == data.name) {

							document.getElementsByClassName(snake.data.lists[i][data.index].name)[data.index].style.left = document.getElementsByClassName(snake.data.lists[i][data.index].name)[data.index].offsetLeft - 50 + 'px'

						}
					}

				})

				snake.data.socket.on('doright', function(data) {
					snake.data.lists = data.data

					for(var i = 0; i < snake.data.lists.length; i++) {
						if(snake.data.lists[i][0].name == data.name) {

							document.getElementsByClassName(snake.data.lists[i][data.index].name)[data.index].style.left = document.getElementsByClassName(snake.data.lists[i][data.index].name)[data.index].offsetLeft + 50 + 'px'

						}
					}

				})
                snake.data.socket.on('dodirl',function(data){
                	snake.data.lists = data.data
                   console.log(data.name)
							document.getElementsByClassName(data.name)[0].setAttribute('src', './img/headL.png')
						
						
                })
                snake.data.socket.on('dodirr',function(data){
                	snake.data.lists = data.data
                   console.log(data.name)
							document.getElementsByClassName(data.name)[0].setAttribute('src', './img/headR.png')
						
						
                })
                snake.data.socket.on('dodird',function(data){
                	snake.data.lists = data.data
                   console.log(data.name)
							document.getElementsByClassName(data.name)[0].setAttribute('src', './img/headD.png')
						
						
                })
                snake.data.socket.on('dodirt',function(data){
                	snake.data.lists = data.data
                   console.log(data.name)
							document.getElementsByClassName(data.name)[0].setAttribute('src', './img/headT.png')
						
						
                })
                snake.data.socket.on('dorecl',function(data){
                	snake.data.lists = data.data
                	for(var i = 0; i < snake.data.lists.length; i++) {
                		if(snake.data.lists[i][0].name==data.name){
//              			console.log(snake.data.lists[i][snake.data.lists[i].length])
                			snake.methods.createdBody(snake.data.lists[i][snake.data.lists[i].length-1],snake.data.lists[i].length-1)
                		}
                	}
                  
						
                })
                
                snake.data.socket.on('dorecr',function(data){
                	snake.data.lists = data.data
                	for(var i = 0; i < snake.data.lists.length; i++) {
                		if(snake.data.lists[i][0].name==data.name){
//              			console.log(snake.data.lists[i][snake.data.lists[i].length])
                			snake.methods.createdBody(snake.data.lists[i][snake.data.lists[i].length-1],snake.data.lists[i].length-1)
                		}
                	}
                  
						
                })
                
                snake.data.socket.on('dorecd',function(data){
                	snake.data.lists = data.data
                	for(var i = 0; i < snake.data.lists.length; i++) {
                		if(snake.data.lists[i][0].name==data.name){
//              			console.log(snake.data.lists[i][snake.data.lists[i].length])
                			snake.methods.createdBody(snake.data.lists[i][snake.data.lists[i].length-1],snake.data.lists[i].length-1)
                		}
                	}
                  
						
                })
                
                snake.data.socket.on('dorect',function(data){
                	snake.data.lists = data.data
                	for(var i = 0; i < snake.data.lists.length; i++) {
                		if(snake.data.lists[i][0].name==data.name){
//              			console.log(snake.data.lists[i][snake.data.lists[i].length])
                			snake.methods.createdBody(snake.data.lists[i][snake.data.lists[i].length-1],snake.data.lists[i].length-1)
                		}
                	}
                  
						
                })
                
                snake.data.socket.on('dorecbody',function(data){
                	snake.data.lists = data.data
                	console.log(data.name)
                	$('.'+data.name).remove()
                })
                
                
                snake.data.socket.on('dorecbian',function(data){
                	snake.data.lists = data.data
                	console.log(data.name)
                	$('.'+data.name).remove()
                })
				/*snake.data.socket.on('dojoin2',function(data){
					console.log('c')
					snake.methods.stratPosition(data)
				})*/
			},
			setDan: function(data) {
				
				document.getElementById('dan').style.left = data.x*50+'px'
				document.getElementById('dan').style.top = data.y*50+'px'
			},
			addscore: function(score) {
				document.getElementsByClassName('score')[0].innerHTML = score
			},
			rectange: function() {
				//				console.log(snake.data.list[0].x*50+'---'+snake.data.dom.offsetLeft)

				if(snake.data.list[0].x * 50 == snake.data.dom.offsetLeft && snake.data.list[0].y * 50 == snake.data.dom.offsetTop) {
					var len = snake.data.list.length - 1
					switch(snake.data.list[len].dir) {
						case 'left':
							snake.data.list.push({
								x: snake.data.list[len].x + 1,
								y: snake.data.list[len].y,
								dir: snake.data.list[len].dir,
								name:sessionStorage.getItem('name'),
								src: './img/add.png'
							})
							snake.data.socket.emit('recl',{data:snake.data.list,name:sessionStorage.getItem('name')})
							snake.data.score++
								this.addscore(snake.data.score)
							break;
						case 'top':
							snake.data.list.push({
								x: snake.data.list[len].x,
								y: snake.data.list[len].y + 1,
								name:sessionStorage.getItem('name'),
								dir: snake.data.list[len].dir,
								src: './img/add.png'
							})
							snake.data.socket.emit('rect',{data:snake.data.list,name:sessionStorage.getItem('name')})
							snake.data.score++
								this.addscore(snake.data.score)
							break;
						case 'right':
							snake.data.list.push({
								x: snake.data.list[len].x - 1,
								y: snake.data.list[len].y,
								name:sessionStorage.getItem('name'),
								dir: snake.data.list[len].dir,
								src: './img/add.png'
							})
							snake.data.socket.emit('recr',{data:snake.data.list,name:sessionStorage.getItem('name')})
							snake.data.score++
								this.addscore(snake.data.score)
							break;
						case 'down':
							snake.data.list.push({
								x: snake.data.list[len].x,
								y: snake.data.list[len].y - 1,
								name:sessionStorage.getItem('name'),
								dir: snake.data.list[len].dir,
								src: './img/add.png'
							})
							snake.data.socket.emit('recd',{data:snake.data.list,name:sessionStorage.getItem('name')})
							snake.data.score++
								this.addscore(snake.data.score)
							break;

					}
					var h = document.body.offsetHeight
					var num = Math.ceil(h / 50) - 2
					var l = document.body.offsetWidth
					var num2 = Math.ceil(l / 50) - 2
					var p = snake.util.randomRange(0, num)
					var p2 = snake.util.randomRange(0, num2)
					snake.data.socket.emit('dan',{x:p2,y:p})
				}
			},
			rectBian: function(dom) {
				switch(dom.dir) {
					case 'left':
						if(dom.x <= 0) {
							clearInterval(snake.data.t)
							return true

						}
						break;
					case 'top':
						if(dom.y <= 0) {
							clearInterval(snake.data.t)
							return true

						}
						break;
					case 'down':
						if(dom.y * 50 >= document.body.offsetHeight - 70) {
							clearInterval(snake.data.t)
							return true

						}
						break;
					case 'right':

						if(dom.x * 50 >= document.body.offsetWidth - 100) {
							clearInterval(snake.data.t)
							return true

						}
						break;
				}
			},
			rectBody: function() {
				var bo = false
				for(var i = 0; i < snake.data.list.length; i++) {
					if(i == 0) {
						continue
					} else {
						if(snake.data.list[0].x == snake.data.list[i].x && snake.data.list[0].y == snake.data.list[i].y) {
							clearInterval(snake.data.t)
							bo = true
						}
					}

				}
				return bo
			},
			rectOther:function(){
				var others = []
				var bo = false
				for(var i=0;i<snake.data.lists.length;i++){
					if(snake.data.lists[i][0].name==snake.data.list[0].name){
						continue
					}else{
						others.push(snake.data.lists[i])
					}
				}
		        for(var j=0;j<others.length;j++){
		        	for(var k = 0;k<others[j].length;k++){
		        		
		        			if(snake.data.list[0].x==others[j][k].x&&snake.data.list[0].y==others[j][k].y){
		        				bo = true
		        			}
		        		
		        		
		        	}
		        }
		        return bo
			},
			stratPosition: function(data) {
				//				var h = document.body.offsetHeight
				//	  			var num = Math.ceil(h/50)-2
				//	  			var l = document.body.offsetWidth
				//	  			var num2 = Math.ceil(l/50)-2
				//	  			var p = snake.util.randomRange(0,num)
				//	  			var p2 = snake.util.randomRange(0,num2)
				//	  			snake.data.list.push({x:p2,y:p,dir:'top',src:'./img/headT.png'})
				snake.data.lists.push(data)
				for(var i = 0; i < data.length; i++) {
					this.createdBody(data[i], i)
				}
			},
			createdBody: function(item, i) {

				item.dom = document.createElement('img')
				item.dom.setAttribute('src', item.src)
				item.dom.style.position = 'absolute'
				item.dom.style.left = item.x * 50 + 'px'
				item.dom.style.top = item.y * 50 + 'px'
				item.dom.style.height = '50px'
				item.dom.style.width = '50px'
				item.dom.setAttribute('class', item.name)
				if(item.name == sessionStorage.getItem('name')) {

					snake.data.list[i].dom = item.dom
				}
				//				item.dom.style.backgroundColor = 'black'
				//              snake.data.list[i].dom = item.dom
				document.body.appendChild(item.dom)
				//				console.log(snake.data.list[i])
				//				console.log(snake.data.lists)

			},
			loopani: function() {

				snake.data.t = setInterval(function() {
					if(snake.methods.rectBian(snake.data.list[0])) {
						clearInterval(snake.data.t)
						//					document.body.removeChild(document.getElementsByTagName('img'))
						document.getElementById('game-over').style.display = 'block'
						document.getElementById('game-over').getElementsByTagName('p')[1].innerHTML = '分数:' + snake.data.score
						snake.data.score = 0
						snake.methods.addscore(snake.data.score)
						snake.data.list.splice(0,snake.data.length)
						snake.data.lists.splice(0,snake.data.lists)
						snake.data.dir = 'top'
						$('img:not(#dan)').remove()
						snake.data.socket.emit('recbian',{name:sessionStorage.getItem('name')})
						return
					}
					if(snake.methods.rectBody()) {
						clearInterval(snake.data.t)
						//						document.body.removeChild(document.getElementsByTagName('img'))
						document.getElementById('game-over').style.display = 'block'
						document.getElementById('game-over').getElementsByTagName('p')[1].innerHTML = '分数:' + snake.data.score
						snake.data.score = 0
						snake.methods.addscore(snake.data.score)
						snake.data.list.splice(0,snake.data.length)
						snake.data.lists.splice(0,snake.data.lists)
						snake.data.dir = 'top'
						$('img:not(#dan)').remove()
						snake.data.socket.emit('recbody',{name:sessionStorage.getItem('name')})
						return
					}
					if(snake.methods.rectOther()){
						clearInterval(snake.data.t)
						//						document.body.removeChild(document.getElementsByTagName('img'))
						document.getElementById('game-over').style.display = 'block'
						document.getElementById('game-over').getElementsByTagName('p')[1].innerHTML = '分数:' + snake.data.score
						snake.data.score = 0
						snake.methods.addscore(snake.data.score)
						snake.data.list.splice(0,snake.data.length)
						snake.data.lists.splice(0,snake.data.lists)
						snake.data.dir = 'top'
						$('img:not(#dan)').remove()
						snake.data.socket.emit('recbody',{name:sessionStorage.getItem('name')})
						return
					}
					for(var i = 0; i < snake.data.list.length; i++) {
						if(snake.data.list[i].dir == 'left') {

							snake.data.list[i].x = snake.data.list[i].x - 1
							snake.data.socket.emit('dleft', {
								data: snake.data.list,
								index: i
							})
						}
						if(snake.data.list[i].dir == 'top') {
							snake.data.list[i].y = snake.data.list[i].y - 1

							snake.data.socket.emit('dtop', {
								data: snake.data.list,
								index: i
							})

						}
						if(snake.data.list[i].dir == 'right') {

							snake.data.list[i].x = snake.data.list[i].x + 1
							snake.data.socket.emit('dright', {
								data: snake.data.list,
								index: i
							})
						}
						if(snake.data.list[i].dir == 'down') {
							//							    snake.data.list[i].dom.style.top = snake.data.list[i].dom.offsetTop+50+'px'	
							snake.data.list[i].y = snake.data.list[i].y + 1
							snake.data.socket.emit('ddown', {
								data: snake.data.list,
								index: i
							})
						}

					}
					snake.methods.rectange()

				}, snake.data.drution)
			},
			setdirect: function(dir) {
//				snake.data.dir = dir
//				clearInterval(t)
				var j = 1
                 snake.data.list[0].dir = dir
                 
				var t = setInterval(function() {
					if(j < snake.data.list.length) {
						snake.data.list[j].dir = dir
						j++
					} else {
						j = 0
						clearInterval(t)
					}
				}, snake.data.drution)
			}
		},
		bindevent: function() {
			document.addEventListener('keypress', function() {
				switch(event.keyCode) {
					case 119: //上

						if(snake.data.dir == 'down') {
							return
						} else {
							snake.data.dir = 'top'
							snake.data.socket.emit('dirt',{data:snake.data.list,name:sessionStorage.getItem('name')})
							
							snake.methods.setdirect('top')
						}
						break;
					case 115: //下

						if(snake.data.dir == 'top') {
							return
						} else {
							snake.data.dir = 'down'
							snake.data.socket.emit('dird',{data:snake.data.list,name:sessionStorage.getItem('name')})
							
							snake.methods.setdirect('down')
						}
						break;
					case 97: //左
						//					alert(snake.data.dir)
						if(snake.data.dir == 'right') {
							return
						} else {

							snake.data.dir = 'left'
							snake.data.socket.emit('dirl',{data:snake.data.list,name:sessionStorage.getItem('name')})							
							snake.methods.setdirect('left')
						}
						break;
					case 100: //右
						if(snake.data.dir == 'left') {
							return
						} else {
							snake.data.dir = 'right'
							snake.data.socket.emit('dirr',{data:snake.data.list,name:sessionStorage.getItem('name')})
							
							snake.methods.setdirect('right')
						}
						break;
				}
			})
		}
	}
	return snake
})(window, document)

if(sessionStorage.getItem('name')) {
	document.getElementById('input').style.display = 'none'
	snake.initsnake()
} else {
	document.getElementById('input').style.display = 'block'
	document.addEventListener('keydown', function() {
		if(event.keyCode == 13) {
			if(document.getElementById('input').getElementsByTagName('input')[0].value == '') {
				alert('用户名不能为空')
			} else {
				
				sessionStorage.setItem('name', document.getElementById('input').getElementsByTagName('input')[0].value)
				document.getElementById('input').style.display = 'none'
				snake.initsnake()
			}

		}
	})
}

window.onbeforeunload = function () {
//  alert("取消离开");
    //  这是用来设定一个时间, 时间到了, 就会执行一个指定的 method。 
    // setTimeout(onunloadcancel, 3);
    if (event.clientX <= 0 && event.clientY < 0) {
      console.log("关闭");
    }
    else {
      snake.data.socket.emit('recbian',{name:sessionStorage.getItem('name')})
    }
//  return "真的离开?";
  }



function moveUp(){
	if(document.getElementById('game-over').style.display=='block'){
		window.history.back()
	}else{
		if(snake.data.dir == 'down') {
							return
						} else {
							snake.data.dir = 'top'
							snake.data.socket.emit('dirt',{data:snake.data.list,name:sessionStorage.getItem('name')})
							
							snake.methods.setdirect('top')
						}
	}
	
}

function moveLeft(){
	if(snake.data.dir == 'right') {
							return
						} else {

							snake.data.dir = 'left'
							snake.data.socket.emit('dirl',{data:snake.data.list,name:sessionStorage.getItem('name')})
							

							snake.methods.setdirect('left')
						}
}


function moveDown(){
	if(snake.data.dir == 'top') {
							return
						} else {
							snake.data.dir = 'down'
							snake.data.socket.emit('dird',{data:snake.data.list,name:sessionStorage.getItem('name')})
							
							snake.methods.setdirect('down')
						}
}

function moveRight(){
	if(snake.data.dir == 'left') {
							return
						} else {
							snake.data.dir = 'right'
							snake.data.socket.emit('dirr',{data:snake.data.list,name:sessionStorage.getItem('name')})
							
							snake.methods.setdirect('right')
						}
						
}

var controllerOptions = {
				enableGestures: true
			}
var controller = Leap.loop(controllerOptions, function(frame) { //创建控制器连接leapserve
		if(frame.hands.length > 0) {
    	frame.hands.forEach(function(val, index) {//遍历手
    	  var hand = val
    	  var grabStrength = hand.grabStrength
    	 
    	  if(grabStrength>=0.8&&document.getElementById('game-over').style.display=='block'){
    	  	window.location.reload()
    	  }
    	})
    }
})